//
//  ReminderView.m
//  Coding
//
//  Created by dllo on 16/7/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ReminderView.h"
#import "Masonry.h"
#import "HLMacro.h"

@interface ReminderView ()

@property (nonatomic, strong) UIView *view;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, assign) CGFloat time;
@property (nonatomic, assign) HLAlertViewPosition position;

@end

@implementation ReminderView

+ (instancetype)reminderWithSuperView:(id)view andTitle:(NSString *)title andPosition:(HLAlertViewPosition)position
{
    return [[ReminderView alloc]initWithSuperview:view andTitle:title andPosition:position];
}

- (instancetype)initWithSuperview:(id)view andTitle:(NSString *)title andPosition:(HLAlertViewPosition)position
{
    self = [super init];
    if (self) {
        _view = view;
        _title = title;
        _time = 0;
        _position = position;
        [self config];
    }
    return self;
}

- (void)config
{
    [_view addSubview:self];
    self.backgroundColor = [UIColor clearColor];
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        if (_position == HLAlertViewPositionDown) {
            make.top.equalTo(_view.mas_bottom);
        } else if (_position == HLAlertViewPositionUp) {
            make.bottom.equalTo(_view.mas_top);
        } else {
            make.center.equalTo(_view);
        }
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.left.equalTo([UIApplication sharedApplication].windows[0]);
    }];
    self.layer.cornerRadius = 5;
    UILabel *label = [[UILabel alloc]init];
    [self addSubview:label];
    label.font = [UIFont systemFontOfSize:14];
    label.text = _title;
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor colorWithWhite:0 alpha:0.8];
    label.textColor = [UIColor whiteColor];
    label.layer.masksToBounds = YES;
    label.layer.cornerRadius = 5;
    label.tag = 999;
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.centerY.equalTo(self);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(_title.length * 14 + 20);
    }];
    [NSTimer scheduledTimerWithTimeInterval:1/24.0 target:self selector:@selector(finishTimer:) userInfo:@{} repeats:YES];
    
}

- (void)finishTimer:(NSTimer *)time
{
    _time = _time + time.timeInterval;
    UILabel *label = [self viewWithTag:999];
    if (_time < 1) {
        return;
    } else if (_time >= 1.5) {
        [time invalidate];
        [label removeFromSuperview];
        [self removeFromSuperview];
    } else {
        label.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.5 - _time];
    }
    
   
}

@end
